package com.dirk.happie.activities;

import java.io.File;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.dirk.happie.R;
import com.dirk.happie.beans.BasketItem;
import com.dirk.happie.network.RequestCompleteListener;
import com.dirk.happie.network.SetOrderTask;
import com.dirk.happie.utils.App;
import com.dirk.happie.utils.Availablity;
import com.dirk.happie.utils.Common;
import com.dirk.happie.utils.Keys;
import com.dirk.happie.utils.LogoDownloader;

public class PickupActivity extends Activity {
	Button orderButton;
	private TextView datePicker;
	private TextView timePicker;
	private Calendar c;
	private int mYear;
	private int mMonth;
	private int mDay;
	private int hour;
	private int minute;
	private LinearLayout layoutTop;
	private float totalPrice;
	private App mApp;

	private SetOrderTask setOrderTask = null;

	private LogoDownloader logoDownloader = null;
	private String cacheFolderPath = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pickup);
		this.mApp = ((App) getApplication());
		ImageView companyLogoView = (ImageView) findViewById(R.id.img_company);
		cacheFolderPath = Environment.getExternalStorageDirectory().getPath() + "/happie_cache";
		File file = new File(cacheFolderPath);
		file.mkdirs();
		logoDownloader = new LogoDownloader();
		if (mApp.getCompanyLogo() != null) {
			logoDownloader.download(Keys.LOGOS_URL + mApp.getCompanyLogo(), cacheFolderPath + "/" + Common.getMD5(mApp.getCompanyLogo()), companyLogoView);
		}
		createView();
		
		buttonListeners();

		pickerListeners();

		footerMenuListeners();
	}

	private void buttonListeners() {
		orderButton = (Button) findViewById(R.id.btn_order);
		orderButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				String order = getOrderString();
				setOrder(order);
			}
		});
	}

	private void setOrder(String order) {

		setOrderTask = new SetOrderTask(this);
		setOrderTask.setRequestCompleteListener(new RequestCompleteListener<String>() {

			@Override
			public void onSuccess(String result) {
				JSONArray jsonArray;
				JSONObject json = null;
				try {
					jsonArray = new JSONArray(result);
					json = jsonArray.getJSONObject(0);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				if (json != null && json.has("error")) {
					result = json.optString("error");
					Toast.makeText(PickupActivity.this, result, Toast.LENGTH_SHORT).show();
				}
				if (json != null && json.has("apimsg")) {
					result = json.optString("apimsg");
					Toast.makeText(PickupActivity.this, result, Toast.LENGTH_SHORT).show();
					mApp.getBasketList().clear();
					mApp.getHappie_prefs().edit().putString("BasketList", "[]").commit();
					Intent intent = new Intent(PickupActivity.this, ThankYouActivity.class);
					intent.putExtra("Date", datePicker.getText().toString());
					intent.putExtra("Time", timePicker.getText().toString());
					startActivityForResult(intent, 10);
				}

			}

			@Override
			public void onFailure(String message) {
			}
		});
		if (Availablity.isNetworkAvailable(this)) {
			setOrderTask.execute(order);
		} else {
			Toast.makeText(this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
		}
	}

	private String getOrderString() {
		JSONObject orderdata = new JSONObject();
		try {
//			JSONObject addressJson = new JSONObject();
//
//			addressJson.putOpt("city", mApp.getHappie_prefs().getString(Keys.KEY_CITY, ""));
//			addressJson.putOpt("street", mApp.getHappie_prefs().getString(Keys.KEY_STREET, ""));
//			addressJson.putOpt("apt", mApp.getHappie_prefs().getString(Keys.KEY_APT_NO, ""));
//			addressJson.putOpt("zip", mApp.getHappie_prefs().getString(Keys.KEY_ZIP, ""));

			orderdata.putOpt("user", mApp.getUserId());
			orderdata.putOpt("company", mApp.getCompanyId());
			orderdata.putOpt("address", mApp.getHappie_prefs().getString(Keys.KEY_ADDRESS, ""));
			orderdata.putOpt("orderway", 1);
			orderdata.putOpt("ordertime", datePicker.getText().toString() + " " + timePicker.getText().toString());

			JSONArray orderline = new JSONArray();
			for (BasketItem item : mApp.getBasketList()) {
				if (item.getIdExtra() == null || item.getIdExtra().equals("")) {
					JSONObject orderItem = new JSONObject();
					if (item.getIdOption() == null || item.getIdOption().equals("")) {
						orderItem.putOpt("id", item.getIdArticle());
					} else {
						orderItem.putOpt("id", item.getIdOption());
					}
					orderItem.putOpt("type", item.getType());
					orderItem.putOpt("quantity", item.getCount());
					JSONArray extraArray = new JSONArray();
					boolean hasExtra = false;
					for (BasketItem itemExtra : mApp.getBasketList()) {
						if (itemExtra.getIdExtra() != null && !itemExtra.getIdExtra().equals("") && itemExtra.getIdOption() != null && item.getType().equals(itemExtra.getType()) && item.getIdArticle().equals(itemExtra.getIdArticle()) && item.getIdOption().equals(itemExtra.getIdOption())) {
							hasExtra = true;
							extraArray.put(itemExtra.getIdExtra());
						}
					}
					if (hasExtra) {
						orderItem.putOpt("extra", extraArray);
					}
					orderline.put(orderItem);
				}
			}
			orderdata.putOpt("orderline", orderline);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		String order = orderdata.toString();
		Log.i("order", order);
		return order;
	}

	private void createView() {

		layoutTop = (LinearLayout) findViewById(R.id.linearTop);

		createProductLayouts();

		TextView priceTotal = (TextView) findViewById(R.id.priceTotal);
		priceTotal.setText(getString(R.string.currency) + " " + Common.getPrice(Float.toString(totalPrice)));

	}

	private void createProductLayouts() {
		for (int i = 0; i < mApp.getBasketList().size(); i++) {
			RelativeLayout relativeLayout = new RelativeLayout(this);
			relativeLayout.setPadding(5, 5, 5, 5);
			// layout.setGravity(Gravity.FILL_HORIZONTAL);

			totalPrice += Integer.parseInt(mApp.getBasketList().get(i).getCount()) * Float.parseFloat(Common.getPrice(mApp.getBasketList().get(i).getPrice()));
			LinearLayout linearLayout = new LinearLayout(this);
			linearLayout.setOrientation(LinearLayout.HORIZONTAL);

			TextView textCount = new TextView(this);
			textCount.setPadding(5, 5, 5, 5);
			textCount.setText(mApp.getBasketList().get(i).getCount());
			textCount.setId(i);
			textCount.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
			textCount.setGravity(Gravity.LEFT);

			linearLayout.addView(textCount);

			TextView textTitle = new TextView(this);
			textTitle.setPadding(5, 5, 5, 5);
			if (mApp.getBasketList().get(i).getIdExtra() == null) {
				textTitle.setText(mApp.getBasketList().get(i).getName() + "\n" + mApp.getBasketList().get(i).getSize());
			} else {
				textTitle.setText(mApp.getBasketList().get(i).getName());
			}
			textTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
			textTitle.setGravity(Gravity.LEFT);

			linearLayout.addView(textTitle);

			relativeLayout.addView(linearLayout);

			RelativeLayout.LayoutParams paramsPrice = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
			paramsPrice.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
			paramsPrice.addRule(RelativeLayout.CENTER_VERTICAL);
			TextView textPrice = new TextView(this);
			textPrice.setText(getString(R.string.currency) + " " + Common.getPrice(mApp.getBasketList().get(i).getPrice()));
			textPrice.setGravity(Gravity.RIGHT);
			textPrice.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
			textPrice.setLayoutParams(paramsPrice);

			relativeLayout.addView(textPrice);

			layoutTop.addView(relativeLayout);

		}
	}

	private void pickerListeners() {
		datePicker = (TextView) findViewById(R.id.textPicupDate);
		datePicker.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDatePickerDialog();
			}
		});

		timePicker = (TextView) findViewById(R.id.textPicupTime);
		timePicker.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showTimePickerDialog();
			}
		});
		c = Calendar.getInstance();
		c.add(Calendar.MINUTE, 15);
		getAvailableTime();

	}

	private void getAvailableTime() {

		if (!Availablity.isOpen(mApp.getSettings(), c) || !Availablity.isPickupAvailable(mApp.getSettings(), c)) {
			Toast.makeText(PickupActivity.this, getString(R.string.time_not_available), Toast.LENGTH_SHORT).show();
		}

		c = Availablity.getAvailableTime(c, PickupActivity.this);

		while (!Availablity.isOpen(mApp.getSettings(), c)) {
			c.add(Calendar.DAY_OF_MONTH, 1);
		}
		
		int k=0;
		while (!Availablity.isOpenDayOfWeek(mApp.getSettings(), c) && k<15) {
			c.add(Calendar.DAY_OF_MONTH, 1);
			k++;
		}
		
		if (k==15) {
			showMessageDialog(getString(R.string.not_available));
			orderButton.setVisibility(View.GONE);
			return;
		}
		
		while (!Availablity.isPickupAvailable(mApp.getSettings(), c)) {
			c.add(Calendar.MINUTE, 1);
		}

		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		hour = c.get(Calendar.HOUR_OF_DAY);
		minute = c.get(Calendar.MINUTE);

		updateDateDisplay();

		updateTimeDisplay();
	}

	private void updateDateDisplay() {
		datePicker.setText(new StringBuilder()
		// Month is 0 based so add 1
				.append(Common.pad(mDay)).append("-").append(Common.pad(mMonth + 1)).append("-").append(mYear).append(" "));
	}

	private void updateTimeDisplay() {
		timePicker.setText(new StringBuilder()

		.append(Common.pad(hour)).append(":").append(Common.pad(minute)));

	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			c.set(Calendar.YEAR, year);
			c.set(Calendar.MONTH, monthOfYear);
			c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			getAvailableTime();

		}
	};

	private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
			c.set(Calendar.HOUR_OF_DAY, selectedHour);
			c.set(Calendar.MINUTE, selectedMinute);
			getAvailableTime();

		}
	};

	private void showDatePickerDialog() {
		DatePickerDialog dateDialog = new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);

		dateDialog.show();

	}

	private void showTimePickerDialog() {
		TimePickerDialog timeDialog = new TimePickerDialog(this, timePickerListener, hour, minute, true);

		timeDialog.show();

	}

	private void footerMenuListeners() {

		View homeButton = findViewById(R.id.home);
		homeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setResult(100);
				finish();
			}
		});

		View categoriesButton = findViewById(R.id.categories);
		categoriesButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setResult(200);
				finish();
			}
		});

		View basketButton = findViewById(R.id.basket);
		basketButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		View searchButton = findViewById(R.id.search);
		searchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		setResult(resultCode);
		switch (resultCode) {
		case 100:
			finish();
			break;

		case 200:
			finish();
			break;

		case 300:
			finish();
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	public Dialog alertDialog;
	public void showMessageDialog(String message) {
		if (alertDialog != null && alertDialog.isShowing())
			return;

		alertDialog = new Dialog(this);
		alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		alertDialog.setContentView(R.layout.dialog);
		alertDialog.setCancelable(false);

		TextView text = (TextView) alertDialog.findViewById(R.id.dialog_title);
		text.setTextSize(18);
		text.setText(message);

		Button okButton = (Button) alertDialog.findViewById(R.id.ok_button);
		okButton.setText(R.string.ok_error);
		okButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				alertDialog.cancel();
				finish();
				
			}
		});
		alertDialog.show();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_pickup, menu);
		return true;
	}

	@Override
	protected void onDestroy() {
		if (logoDownloader != null) {
			logoDownloader.clearImages();
		}
		if (setOrderTask != null) {
			setOrderTask.setRequestCompleteListener(null);
		}
		super.onDestroy();
	}

}
